<?php

namespace App\Services;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use App\Models\SmsModel;

/**
 * 阿里云短信服务1
 */
trait SmsService
{

    /**
     * 发送短信
     * @param string $phoneNumbers 手机号
     * @param string $templateParam 短信模板参数
     * @return bool|string
     * @throws
     */
    public function sendSms(string $phoneNumbers, string $action, array $templateParam)
    {
        $smsConfig = SmsModel::first();
        if (!$smsConfig) {
            return false;
        }
        if (!$smsConfig->status) {
            return false;
        }
        $accessKeyId = $smsConfig->key;
        $accessKeySecret = $smsConfig->secret;
        $signName = $smsConfig->sign;
        $template = $smsConfig->template;
        if ($template) {
            $template = json_decode($template, true);
            $templateCode = $template[$action];
        }
        return self::main($accessKeyId, $accessKeySecret, $phoneNumbers, $signName, $templateCode, $templateParam);
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($accessKeyId, $accessKeySecret, $phoneNumbers, $signName, $templateCode, $templateParam)
    {
        $client = self::createClient($accessKeyId, $accessKeySecret);
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phoneNumbers,
            "signName" => $signName,
            "templateCode" => $templateCode,
            "templateParam" => json_encode($templateParam)
        ]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $a = $client->sendSmsWithOptions($sendSmsRequest, new RuntimeOptions([]));
            return ['code'=>1, 'data'=>$a];
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            return ['code'=>0, 'msg'=>$error->message];
            // 如有需要，请打印 error
            Utils::assertAsString($error->message);
        }
    }
}
